package com.example.app.pages.main.home.addNew.addRecord.viewModel

import androidx.compose.ui.text.input.TextFieldValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.app.components.MyTextField.MyTextFieldState
import com.example.app.data.bean.AccountCat
import com.example.app.data.bean.AccountTitle
import com.example.app.data.bean.BaseResponseData
import com.example.app.data.bean.routeAddAccount.TitlesAndCats
import com.example.app.network.api.AccountService
import com.example.app.util.CacheUtil
import com.example.app.viewmodel.MainViewModel
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import retrofit2.HttpException

class AddRecordViewModel(var mainViewModel: MainViewModel) : ViewModel() {
    //收入备注
    var incomeRemarkInputState = MyTextFieldState()
    //支出备注
    var payRemarkInputState = MyTextFieldState()
    // 收入
    var incomeMoneyInputState = MyTextFieldState()
    // 支出
    var payMoneyInputState = MyTextFieldState()
    //所有title
    var _allTitles = MutableStateFlow<List<AccountTitle>?>(null)
    var allTitles = _allTitles.asStateFlow()
    fun flowUpdate_allTitles(value: List<AccountTitle>) {
        _allTitles.update {
            value.toMutableList()
        }
    }
    //所有cats
    var _allCats = MutableStateFlow<List<AccountCat>?>(null)
    var allCats = _allCats.asStateFlow()
    fun flowUpdate_allCats(value: List<AccountCat>) {
        _allCats.update {
            value.toMutableList()
        }
    }
    //获取所有的分类和标题
    fun request_getAllCatsAndTitles(
            AccountType: Boolean? = null,
            CreatorId: String = CacheUtil.getUserId()
    ): Deferred<BaseResponseData<TitlesAndCats>> {
        return viewModelScope.async {
            
            try {
                var result = viewModelScope.async {
                    AccountService.service.titlesAndCats(
                        AccountType = AccountType,
                        CreatorId = CreatorId
                    )
                }
                    .await()
                
                mainViewModel.requestHandler(result)
                return@async result
            } catch (e: HttpException) {
                var result = viewModelScope.async {
                    BaseResponseData<TitlesAndCats>(
                        code = e.code(),
                        data = null,
                        msg = e.message.toString()
                    )
                }
                    .await()
                
                mainViewModel.requestHandler(result)
                return@async result
            }
        }
    }
}